package luj.groovy.excel.internal.table.body

import luj.groovy.excel.api.table.body.Body
import luj.groovy.excel.internal.table.header.TableHeaderMaker
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet

import java.util.stream.Collectors
import java.util.stream.IntStream

class TableBodyMaker {

  TableBodyMaker(Sheet sheet, TableHeaderMaker.Result header) {
    _sheet = sheet
    _header = header
  }

  Body make() {
    int startRow = _header.lastRow() + 1
    int lastRow = _sheet.lastRowNum

    def body = new BodyImpl()
    body._rowList = IntStream.rangeClosed(startRow, lastRow)
        .mapToObj() { _sheet.getRow(it) }
        .map { makeRow(it) }
        .collect(Collectors.toList())

    return body
  }

  private RowImpl makeRow(Row excelRow) {
    int startCol = _header.firstColumn()
    int lastCol = _header.lastColumn()

    def row = new RowImpl()
    row._value = IntStream.rangeClosed(startCol, lastCol)
        .mapToObj() { excelRow.getCell(it) }
        .map { CellValueGetter.GET.getValue(it) }
        .collect(Collectors.toList())

    return row
  }

  private final Sheet _sheet

  private final TableHeaderMaker.Result _header
}
